package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.MachineDTO;
import com.example.vendingmachine.dto.MachineQuery;
import com.example.vendingmachine.entity.Machine;
import com.example.vendingmachine.service.MachineService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 设备管理控制器
 */
@RestController
@RequestMapping("/api/machines")
@RequiredArgsConstructor
public class MachineController {

    private final MachineService machineService;

    /**
     * 分页查询设备列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('machine:list')")
    public Result<PageInfo<Machine>> list(MachineQuery query) {
        return Result.success(machineService.listMachines(query));
    }

    /**
     * 获取设备详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('machine:list')")
    public Result<Machine> getInfo(@PathVariable Long id) {
        return Result.success(machineService.getMachineById(id));
    }

    /**
     * 新增设备
     */
    @PostMapping
    @PreAuthorize("hasAuthority('machine:add')")
    public Result<Long> add(@Validated @RequestBody MachineDTO machineDTO) {
        return Result.success(machineService.createMachine(machineDTO));
    }

    /**
     * 更新设备
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('machine:edit')")
    public Result<Void> update(@PathVariable Long id, @Validated @RequestBody MachineDTO machineDTO) {
        machineDTO.setId(id);
        machineService.updateMachine(machineDTO);
        return Result.success();
    }

    /**
     * 删除设备
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('machine:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        machineService.deleteMachine(id);
        return Result.success();
    }

    /**
     * 更新设备状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('machine:edit')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam String status) {
        machineService.updateMachineStatus(id, status);
        return Result.success();
    }

    /**
     * 更新设备在线状态
     */
    @PutMapping("/{id}/online-status")
    @PreAuthorize("hasAuthority('machine:edit')")
    public Result<Void> updateOnlineStatus(@PathVariable Long id, @RequestParam String status) {
        machineService.updateOnlineStatus(id, status);
        return Result.success();
    }

    /**
     * 检查点位下是否有设备
     */
    @GetMapping("/check-point")
    @PreAuthorize("hasAuthority('machine:list')")
    public Result<Boolean> hasMachinesByPointId(@RequestParam Long pointId) {
        return Result.success(machineService.hasMachinesByPointId(pointId));
    }
} 